#include "databasehandler.h"
#include <QDebug>
#include <QCoreApplication>

// 初始化数据库连接
DatabaseHandler::DatabaseHandler()
{

    if (!initDatabase()) {
        qCritical() << "数据库初始化失败";
    }
}
// 关闭数据库连接
DatabaseHandler::~DatabaseHandler()
{

    if (m_db.isOpen()) {
        m_db.close();
    }
}

DatabaseHandler &DatabaseHandler::instance()
{
    static DatabaseHandler instance;
    return instance;
}
// 添加SQLite数据库驱动
bool DatabaseHandler::initDatabase()
{
    qDebug() << "开始初始化";

    m_db = QSqlDatabase::addDatabase("QSQLITE");

    // 设置数据库路径（当前应用程序目录下的pro.db）
    //QString dbPath = QCoreApplication::applicationDirPath() + "./pro.db";
   // qDebug() << dbPath;
    m_db.setDatabaseName("./pro.db");

    // 打开数据库
    if (!m_db.open()) {
        qCritical() << "无法打开数据库:" << m_db.lastError().text();
        return false;
    }

    // 如果用户表不存在则创建
    QSqlQuery query;
    QString createTableSql = "CREATE TABLE IF NOT EXISTS users ("
                            "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                            "username TEXT NOT NULL UNIQUE, "
                            "password_hash TEXT NOT NULL, "
                            "salt TEXT NOT NULL, "
                            "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";

    if (!query.exec(createTableSql)) {
        qCritical() << "创建用户表失败:" << query.lastError().text();
        return false;
    }

    return true;
}

QVariantMap DatabaseHandler::getUserByName(const QString &username)
{
    QVariantMap userData;

    if (!isDatabaseConnected()) {
        return userData;
    }

    QSqlQuery query;
    // 使用参数化查询防止SQL注入
    query.prepare("SELECT id, username, password_hash, salt FROM users WHERE username = :username");
    query.bindValue(":username", username);

    if (!query.exec()) {
        qWarning() << "查询用户失败:" << query.lastError().text();
        return userData;
    }

    // 如果查询到用户
    if (query.next()) {
        userData["id"] = query.value("id");
        userData["username"] = query.value("username");
        userData["password_hash"] = query.value("password_hash");
        userData["salt"] = query.value("salt");
    }

    return userData;
}

bool DatabaseHandler::isDatabaseConnected() const
{
    return m_db.isOpen();
}
